/**
 * 
 */
package com.oauth.auth.controllers;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.oauth.auth.constants.AuthConstants;

/**
 * @author asanthan
 * 
 */
@Controller
public class LoginController {

	@Value("login")
	private String mViewName;

	@Value("${auth.home.url}")
	private String mHomePage;

	@RequestMapping("/auth/login")
	public ModelAndView handleRequest(HttpServletRequest pRequest, HttpServletResponse pResponse)
			throws ServletException, IOException {
		ModelAndView modelAndView = new ModelAndView();

		String returnUrl = pRequest.getParameter(AuthConstants.PARAM_RETURN_URL);
		if (returnUrl == null) {
			returnUrl = getHomePage();
		}
		UserService userService = UserServiceFactory.getUserService();

		if (userService != null && userService.getCurrentUser() != null) {
			pResponse.sendRedirect(getHomePage());
			return modelAndView;
		}

		String googleLoginUrl = userService.createLoginURL(returnUrl);

		modelAndView.addObject(AuthConstants.LOGIN_URL, googleLoginUrl);
		modelAndView.setViewName(getViewName());

		return modelAndView;
	}

	/**
	 * @return the viewName
	 */
	public String getViewName() {
		return mViewName;
	}

	/**
	 * @param pViewName
	 *            the viewName to set
	 */
	public void setViewName(String pViewName) {
		mViewName = pViewName;
	}

	/**
	 * @return the homePage
	 */
	public String getHomePage() {
		return mHomePage;
	}

	/**
	 * @param pHomePage
	 *            the homePage to set
	 */
	public void setHomePage(String pHomePage) {
		mHomePage = pHomePage;
	}

}